#include "utils.h"
#include "math.h"
#include "debug.h"

uchar idata temp[10];
uchar temp_len;

uint pow(uchar base, uchar index)
{
    uchar i;
    uint ret = 1;
    for(i=0; i< index; i++)
    {
        ret *= base;
    }
    return ret;
}

uchar float2char(float num, uchar * str, uchar accuracy)
{
    uchar len, i;
    int inte = (int)num;
    len = num2char(inte, str);

    str += len;
    *str = '.'; //radix point
    num = num - inte;
    num = num < 0 ? -num : num;
    inte = (int)(num * pow(10, accuracy));
    temp_len = num2char(inte, temp);
    if(temp_len < accuracy) // 补足‘0’
    {
        for(i =0; i< accuracy - temp_len; i++)
        {
            str += 1;
            *str = '0';
        }
    }
    user_strcat(str+1, 0, temp);
    len = accuracy + len + 1 ;
    return len;
}

uchar num2char(long num, uchar * str)
{
    uchar i = 0,j,tmp;
    bit minus_flag = 0;
    if(num == 0)
    {
        str[0]='0';
        str[1]='\0';
        return 1;
    }

    if(num < 0)
    {
        minus_flag = 1;
        num = -num;
    }

    while(num>0)
    {
        str[i++] = num % 10 + '0';
        num = num / 10;
    }
    if(minus_flag)
        str[i++] = '-';

    for(j=0; j< i/2; j++)
    {
        tmp = str[j];
        str[j] = str[i-j-1];
        str[i-j-1] = tmp;
    }
    str[i] = '\0';
    return i;
}

void delay(uint i)
{
    while(i--)
    {
        _nop_();
        _nop_();
        _nop_();
        _nop_();
    }
}


void user_strcat(uchar * source, uchar len, uchar * target)
{
    source += len;
    while(*target != '\0')
    {
        *source = *target; 
        source ++;
        target ++;
    }
    *source = '\0';
}